package handler

import (
	"DuckShop/internal/user/database/dal"
	"DuckShop/internal/user/database/model"
	"DuckShop/internal/user/global"
	"DuckShop/internal/user/proto/users"
	"DuckShop/pkg/common"
	"context"
	"fmt"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/timestamppb"
)

type DuckUserServiceServer struct {
	users.UnimplementedDuckUserServiceServer
}

// CovertModelToRPCUser gorm model 转为 rpc struct
func CovertModelToRPCUser(user *model.DuckUser) *users.User {
	return &users.User{
		Id:        uint64(user.ID),
		IsDeleted: user.IsDeleted,
		UserId:    uint64(user.UserID),
		Username:  user.Username,
		Mobile:    user.Mobile,
		Password:  user.Password,
		Nickname:  user.Nickname,
		Birthday:  timestamppb.New(user.Birthday),
		Gender:    user.Gender,
		Role:      user.Role,
	}
}

func (s *DuckUserServiceServer) UpdateUser(ctx context.Context, request *users.UpdateUserRequest) (*users.UpdateUserResponse, error) {
	first, err := dal.DuckUser.Where(dal.DuckUser.UserID.Eq(int64(request.GetUser().UserId))).First()
	if err != nil {
		return nil, status.Errorf(codes.Aborted, "更新用户失败！%s", err.Error())
	}
	salt, err := common.GenerateRandomSalt(18)
	if err != nil {
		return nil, status.Errorf(codes.Aborted, "创建用户异常！%s", err.Error())
	}
	requestUser := request.GetUser()
	password := common.GenPassword(salt, requestUser.Password)
	first.Username = requestUser.Username
	first.Password = password
	first.Username = requestUser.Username
	first.Birthday = requestUser.Birthday.AsTime()
	first.Gender = requestUser.Gender
	first.Role = requestUser.Role
	err = dal.DuckUser.Save(first)
	if err != nil {
		return nil, status.Errorf(codes.Aborted, "更新用户失败！%s", err.Error())
	}
	return &users.UpdateUserResponse{User: CovertModelToRPCUser(first)}, nil
}

func (s *DuckUserServiceServer) DeleteUser(ctx context.Context, request *users.DeleteUserRequest) (*users.DeleteUserResponse, error) {
	first, err := dal.DuckUser.Where(dal.DuckUser.UserID.Eq(int64(request.GetUserId()))).First()
	fmt.Println(first.IsDeleted)
	if err != nil {
		return nil, status.Errorf(codes.Aborted, "删除用户失败！%s", err.Error())
	}
	first.IsDeleted = !first.IsDeleted
	err = dal.DuckUser.Save(first)
	if err != nil {
		return nil, status.Errorf(codes.Aborted, "删除用户失败！%s", err.Error())
	}
	return &users.DeleteUserResponse{UserId: uint64(first.UserID)}, nil
}

func (s *DuckUserServiceServer) ListUsers(ctx context.Context, request *users.ListUsersRequest) (*users.ListUsersResponse, error) {
	count, err := dal.DuckUser.Count()
	if err != nil {
		return nil, status.Errorf(codes.Aborted, "查询用户异常！%s", err.Error())
	}
	find, err := dal.DuckUser.Debug().Scopes(common.Pagination(int(request.GetPageNumber()), int(request.PageSize))).Find()
	if err != nil {
		return nil, status.Errorf(codes.Aborted, "查询用户异常！%s", err.Error())
	}
	us := make([]*users.User, 0, len(find))
	for idx, _ := range find {
		us = append(us, CovertModelToRPCUser(find[idx]))
	}
	return &users.ListUsersResponse{Users: us, Total: uint32(count)}, nil
}

// ValidatePassword 验证用户名和密码是否匹配
func (s *DuckUserServiceServer) ValidatePassword(ctx context.Context, request *users.ValidatePasswordRequest) (*users.ValidatePasswordResponse, error) {
	first, err := dal.DuckUser.Where(dal.DuckUser.Username.Eq(request.GetUsername())).First()
	if err != nil {
		global.DLog.Error(err.Error())
		return &users.ValidatePasswordResponse{IsValid: false}, nil
	}
	ok := common.VerifyPassword(request.GetPassword(), first.Password)
	if ok {
		return &users.ValidatePasswordResponse{IsValid: ok, UserId: uint64(first.UserID)}, nil
	} else {
		return &users.ValidatePasswordResponse{IsValid: ok, UserId: 0}, nil
	}
}

// CreateUser 创建用户
func (s *DuckUserServiceServer) CreateUser(ctx context.Context, req *users.CreateUserRequest) (*users.CreateUserResponse, error) {
	salt, err := common.GenerateRandomSalt(18)
	if err != nil {
		return nil, status.Errorf(codes.Aborted, "创建用户异常！%s", err.Error())
	}
	password := common.GenPassword(salt, req.User.Password)
	user := &model.DuckUser{
		IsDeleted: false,
		UserID:    common.GenSnowflakeID(),
		Username:  req.User.Username,
		Mobile:    req.User.Mobile,
		Password:  password,
		Nickname:  req.User.Nickname,
		Birthday:  req.User.Birthday.AsTime(),
		Role:      req.User.Role,
		Gender:    req.User.Gender,
	}
	err = dal.DuckUser.Create(user)
	if err != nil {
		global.DLog.Error(err.Error())
		return nil, status.Errorf(codes.Aborted, "创建用户异常！%s", err.Error())
	}
	// Return the created user in the response
	resp := &users.CreateUserResponse{
		User: req.User,
	}
	return resp, nil
}
func (s *DuckUserServiceServer) GetUser(ctx context.Context, req *users.GetUserRequest) (*users.GetUserResponse, error) {
	first, err := dal.DuckUser.Where(dal.DuckUser.UserID.Eq(int64(req.UserId))).First()
	if err != nil {
		return nil, status.Errorf(codes.Aborted, "查询用户异常！%s", err.Error())
	}
	return &users.GetUserResponse{User: CovertModelToRPCUser(first)}, nil
}
